import axios from 'axios'
import { dataObjectStorage, dataStorage } from '../func/cache'

/**
 * 省级别的城市列表
 * @param query
 * @returns {Promise<*>}
 */
export function cacheCategory (query = {}) {
  return downListCache('/system/category', query, 'Category', 'Name', 'ID')
}

/**
 * 移除缓存
 * @param key
 */
export function clearCache (key) {
  dataStorage(key, false)
}

/**
 * 分类数据缓存
 * @param requestUrl
 * @param query
 * @param cacheName
 * @param labelKey
 * @param valueKey
 * @returns {Promise<unknown>}
 */
export function downListCache (requestUrl, query = {}, cacheName = '', labelKey = '', valueKey = 'ID') {
  return new Promise(resolve => {
    let cache = dataObjectStorage(cacheName)
    if (cache) {
      resolve(cache)
    } else {
      axios.get(requestUrl, query).then(res => {
        if (res.data.code === 200) {
          let data = res.data.result.list.map(i => {
            return {
              label: i[labelKey],
              value: Number(i[valueKey])
            }
          })
          dataObjectStorage(cacheName, data)
          resolve(data)
        } else {
          resolve([])
        }
      })
    }
  })
}

